package service

import (
	"admin100/app/dao"
	"admin100/app/model"
	"admin100/library/define"
	"admin100/library/define/defErr"
)

var Resource = &resourceService{}

type resourceService struct {
}

func (s *resourceService) FetchResourceOne(pid int) *model.MyadminResource {
	resource, err := dao.MyadminResource.FindOne(dao.MyadminResource.Columns.Id, pid)
	defErr.IfPanic(err, define.DataOptFail)
	if resource == nil {
		return nil
	}
	if resource.ParentId > 0 {
		pResource, pErr := dao.MyadminResource.FindOne(dao.MyadminResource.Columns.Id, resource.ParentId)
		defErr.IfPanic(pErr, define.DataOptFail)
		if pResource == nil {
			return nil
		}

		resource.Parent = model.GetInternalResourceModel(pResource)
	}

	return resource
}

func (s *resourceService) CanParent(sid, pSid int) bool {
	resource := s.FetchResourceOne(sid)
	if resource.ParentId == 0 {
		return false
	}

	pResource := s.FetchResourceOne(pSid)
	if pResource == nil {
		return false
	}

	if pResource.Id == sid {
		return false
	}

	if pResource.Parent == nil && pResource.ParentId == 0 {
		return true
	}
	return false
}

func (s *resourceService) GetParentResourceList(id int) []*model.MyadminResource {
	list := s.List()
	tmpList := make([]*model.MyadminResource, 0)
	if id > 0 {
		for _, e := range list {
			if s.CanParent(id, e.Id) {
				tmpList = append(tmpList, e)
			}
		}
	} else {
		tmpList = list
	}
	return tmpList
}

func (s *resourceService) List() []*model.MyadminResource {
	resource, err := dao.MyadminResource.Limit(100).FindAll()
	defErr.IfPanic(err, define.DataOptFail)

	if resource != nil {
		return s.tranResourceList2ResourceTree(resource)
	}

	return nil
}

func (s *resourceService) tranResourceList2ResourceTree(list []*model.MyadminResource) []*model.MyadminResource {
	//目前这个方法只适合目前项目的二个深度
	var resourceTree = make([]*model.MyadminResource, 0)
	var resourceMap = make(map[int][]*model.MyadminResource)
	//根目录
	for _, v := range list {
		if v.ParentId == 0 {
			resourceTree = append(resourceTree, v)
		}
	}
	// 所有父节点加满他的子节点
	for _, v := range list {
		if v.ParentId > 0 {
			resourceMap[v.ParentId] = append(resourceMap[v.ParentId], v)
		}
	}

	// 将resourceTree父节点加满子节点
	for _, v := range resourceTree {
		if e, ok := resourceMap[v.Id]; ok {
			v.Child = e
		}
	}

	return resourceTree
}
